package utils

import (
	"time"

	"github.com/golang-jwt/jwt"

	"gin-api-server/core_library/global"
)

var defaultJwtSecret = "471281276c11408ddcd6cc62cd3f193148d2728e"

type JwtToken struct {
}

// Encode 加密用户信息
func (t JwtToken) Encode(userId int) (string, error) {
	jwtSecret := global.Config.Jwt.SigningKey
	signkey := []byte(jwtSecret)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"userId":  userId,
		"time":    time.Now().Unix(),
		"exptime": -1,
	})
	tokenStr, err := token.SignedString(signkey)
	if err != nil {
		return "", err
	}
	return tokenStr, nil
}

// Decode 解析token
func (t JwtToken) Decode(tokenString string) int {
	token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
		jwtSecret := global.Config.Jwt.SigningKey
		mySigningKey := []byte(jwtSecret)
		return mySigningKey, nil
	})
	if err != nil {
		return -1
	}
	memberId := token.Claims.(jwt.MapClaims)["userId"].(float64)
	return int(memberId)

}
